<?php

/**
 * Created by PhpStorm.
 * User: luzhaoyang
 * Date: 2017/7/19
 * Time: 14:02
 */
class Image_model extends Base_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('image_lib');
    }

    public function textOverlay($config=array())
    {
        $config['wm_type']='text';
        if (!isset($config['source_image'])||empty($config['source_image'])) {
            echo 'no source image'.PHP_EOL;
            exit();
        }
        //wm_type text text, overlay 设置想要使用的水印处理类型。
        //source_image 设置原图像的名称和路径，路径必须是相对或绝对路径，不能是 URL 。
        //dynamic_output FALSE TRUE/FALSE (boolean)	决定新生成的图像是要写入硬盘还是内存中。 注意，如果是生成到内存的话，一次只能显示一副图像，而且 不能调整它在你页面中的位置，它只是简单的将图像数据以及图像的 HTTP 头发送到浏览器。
        //quality 90% 1-100% 设置图像的品质。品质越高，图像文件越大。
        //wm_padding None A number 内边距，以像素为单位，是水印与图片边缘之间的距离。
        //wm_vrt_alignment bottom top,middle,bottom 设置水印图像的垂直对齐方式。
        //wm_hor_alignment center left,center,right 设置水印图像的水平对齐方式。
        //wm_hor_offset None None 你可以指定一个水平偏移量（以像素为单位）,用于设置水印的位置。偏移量通常是向右移动水印，除非你把水平对齐方式设置为 "right" ，那么你的偏移量将会向左移动水印。
        //wm_vrt_offset None None 你可以指定一个垂直偏移量（以像素为单位）,用于设置水印的位置。偏移量通常是向下移动水印，除非你把垂直对齐方式设置为 "bottom"，那么你的偏移量将会向上移动水印。

        $this->image_lib->initialize($config);
        if (!$this->image_lib->watermark()){
            echo $this->image_lib->display_errors();
            exit();
        }
        $this->image_lib->clear();
    }

    public function resize($config=array())
    {
        if (!isset($config['source_image'])||empty($config['source_image'])) {
            echo 'no source image'.PHP_EOL;
            exit();
        }
        $this->image_lib->initialize($config);
        if (!$this->image_lib->resize()){
            echo $this->image_lib->display_errors();
            exit();
        }
        $this->image_lib->clear();
    }

    public function downloadfromurl($url,$dir,$filename)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);

        curl_close($ch);
        $media = array_merge(array('header'=>$httpinfo),array('body' => $package));

        //生成文件名
        preg_match('/\w\/(\w+)/i', $media["header"]["content_type"], $extmatches);
        $fileExt = $extmatches[1];
        $filename.='.'.$fileExt;
//        $filename = md5(time().uniqid()).".{$fileExt}";

//        $dir="/upload/images/".date('Ymd',time()).'/';
        $fdir = '/home/nldou/webroot/wap'.$dir;
        if(!file_exists($fdir)){
            mkdir($fdir,0775,true);
        }
        file_put_contents($fdir.$filename,$media['body']);
        $url='http://wap.nldou.com'.$dir.$filename;
        return array('filepath'=>$fdir.$filename,'url'=>$url);
    }

    public function downloadwxusericon()
    {
        $dur=time();
        $limit=10;
        $offset=0;
        $this->load->database();
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        try{
            while(true){
                $this->db->reconnect();
                //获取图片地址
                $users=$this->db->select('uid,userIcon')->from('mod_user')->limit($limit,$offset)->get()->result_array();
                if (empty($users)) break;//用户遍历完毕
                foreach ($users as $u){
                    $config=array();
                    if (preg_match("/http:\/\//i",$u['userIcon'])>0){
                        //下载图片
                        $dir='/upload/images/usericons/';
                        $iconpath=$this->downloadfromurl($u['userIcon'],$dir,$u['uid']);
                    }else{
                        //本地图片
                        preg_match('/\w\.(\w+)/i', $u['userIcon'], $extmatches);
                        $config['new_image']='/home/nldou/webroot/wap/upload/images/usericons/'.$u['uid'].'.'.$extmatches[1];
                        $iconpath=array('filepath'=>'/home/nldou/webroot/wap'.$u['userIcon'],
                            'url'=>'http://wap.nldou.com/upload/images/usericons/'.$u['uid'].'.'.$extmatches[1]);
                    }
                    //压缩图片
                    $config['source_image']=$iconpath['filepath'];
                    $config['height']=140;
                    $config['width']=140;
                    $this->resize($config);
                    //保存到redis
                    $redis->set('usericon:'.$u['uid'],$iconpath['url']);
                    echo 'user '.$u['uid'].' '.$iconpath['url'].' saved'.PHP_EOL;
                }
                $offset+=$limit;
            }
            $dur=time()-$dur;
            echo 'complete! totalTime:'.date('i:s',$dur).PHP_EOL;
        }catch (Exception $e){
            $this->db->close();
            echo $e->getMessage().PHP_EOL;
            exit();
        }
    }

    public function fmdkpost()
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();

        $this->load->database();
        $totaluser=$this->db->from('stat_fmdk')->count_all_results();
        $rank1=round($totaluser*0.05);
        $rank2=round($totaluser*0.15)+$rank1;
        $rank3=round($totaluser*0.35)+$rank2;
        $rankindex=1;

//        $globalconfig=array();
//        $globalconfig['wm_font_path']='/home/nldou/webroot/web/fonts/yaheibold.ttf';
//        $globalconfig['wm_font_color']='4c3b3b';
//        $globalconfig['wm_vrt_alignment']='top';
//        $globalconfig['wm_hor_alignment']='left';

        $limit=10;
        $offset=0;
        try{
            while (true){
                $this->db->reconnect();
                $res=$this->db->select('uid,time,books,login,shnum,qnum,ansnum')
                    ->from('stat_fmdk')
                    ->order_by('time DESC ,login DESC ,books DESC ,shnum DESC ,qnum DESC ,ansnum DESC,id ASC')
                    ->limit($limit,$offset)
                    ->get()->result_array();
                if (empty($res)) break;
                foreach ($res as $row){
                    if ($rankindex<$rank1||$rankindex==$rank1){
                        $ranklevel=1;
                    }elseif ($rankindex>$rank1&&$rankindex<$rank2||$rankindex==$rank2){
                        $ranklevel=2;
                    }elseif ($rankindex>$rank2&&$rankindex<$rank3||$rankindex==$rank3){
                        $ranklevel=3;
                    }else{
                        $ranklevel=4;
                    }

                    $redis->zAdd('fmdk:20170606:20170724:rank',$rankindex,$row['uid']);

                    echo 'level:'.$ranklevel.' rank:'.$rankindex.' '.$row['uid'];

//                    $fdir='/home/nldou/webroot/wap/upload/images/fmdk/careerpost/20170606_0724/'.$ranklevel.'/';
//                    if(!file_exists($fdir)){
//                        mkdir($fdir,0775,true);
//                    }
//                    //几本书
//                    $config=$globalconfig;
//                    $config['source_image']='/home/nldou/webroot/web/fmdk-career-'.$ranklevel.'.jpg';
//                    $config['new_image']=$fdir.$row['uid'].'.jpg';
//                    $config['wm_text']=$row['books'];
//                    $config['wm_font_size']='40';
//                    $config['wm_hor_offset']='70';
//                    $config['wm_vrt_offset']='466';
//                    $this->textOverlay($config);
//                    echo ' booknum ok';
//                    //总时长
//                    $config=$globalconfig;
//                    $config['source_image']=$fdir.$row['uid'].'.jpg';
//                    $config['wm_text']=$row['time'];
//                    $config['wm_font_size']='40';
//                    $config['wm_hor_offset']='530';
//                    $config['wm_vrt_offset']='615';
//                    $this->textOverlay($config);
//                    echo ' time ok';
//                    //总天数
//                    $config=$globalconfig;
//                    $config['source_image']=$fdir.$row['uid'].'.jpg';
//                    $config['wm_text']=$row['login'];
//                    $config['wm_font_size']='40';
//                    $config['wm_hor_offset']='340';
//                    $config['wm_vrt_offset']='860';
//                    $this->textOverlay($config);
//                    echo ' days ok';
//                    //提问数
//                    $config=$globalconfig;
//                    $config['source_image']=$fdir.$row['uid'].'.jpg';
//                    $config['wm_text']=$row['qnum'];
//                    $config['wm_font_size']='30';
//                    $config['wm_hor_offset']='80';
//                    $config['wm_vrt_offset']='1020';
//                    $this->textOverlay($config);
//                    echo ' qnum ok';
//                    //回答数
//                    $config=$globalconfig;
//                    $config['source_image']=$fdir.$row['uid'].'.jpg';
//                    $config['wm_text']=$row['ansnum'];
//                    $config['wm_font_size']='30';
//                    $config['wm_hor_offset']='320';
//                    $config['wm_vrt_offset']='1020';
//                    $this->textOverlay($config);
//                    echo ' ansnum ok';
//                    //分享
//                    $config=$globalconfig;
//                    $config['source_image']=$fdir.$row['uid'].'.jpg';
//                    $config['wm_text']=$row['shnum'];
//                    $config['wm_font_size']='30';
//                    $config['wm_hor_offset']='560';
//                    $config['wm_vrt_offset']='1020';
//                    $this->textOverlay($config);
//                    echo ' sharenum ok'.PHP_EOL;

                    $rankindex++;
                }
                $offset+=$limit;
            }
        }catch (Exception $e){
            $this->db->close();
            echo $e->getMessage().PHP_EOL;
            exit();
        }
    }
}